package com.example.flo;

import static androidx.core.content.ContextCompat.getSystemService;


import android.accessibilityservice.AccessibilityService;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityManager;
import android.widget.Button;
import android.widget.Toast;


public class floatview {

    public Context context; // 上下文
    public static floatview floatball;

    private WindowManager wm;
    private int height = 0, width = 0;

    private View view;// 悬浮球view

    WindowManager.LayoutParams params;// 控制悬浮球

    private Handler handler = new Handler();

    private boolean isMoved;// 悬浮球 所需成员变量
    private Runnable longPressRunnable;
    private static final long LONG_PRESS_TIME = ViewConfiguration.getLongPressTimeout(); // 使用系统默认的长按时间

    public floatview(Context context)
    {
        this.context = context;
    }

    public static floatview getInstance(Context context) {
        if (floatball == null) {
            floatball = new floatview(context);
        }
        return floatball;
    }

    @SuppressLint("ClickableViewAccessibility")
    public void createFloatView() {
        if (view == null)
            view = LayoutInflater.from(context).inflate(R.layout.fb, null);

        wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);//获取系统服务WindowManagerService
        height = wm.getDefaultDisplay().getHeight();//获取屏幕宽和高的第一种方法,获取到的值以像素点px为单位
        width = wm.getDefaultDisplay().getWidth();//我们这里具体下来，宽和高分别为1080px,2040px

        params = new WindowManager.LayoutParams();
        // 设置Window Type
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//判断当前版本是否可以使用响应的API
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;//新添加的view,设置为悬浮窗事件
        } else {
            params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
        // 设置悬浮框不可触摸
        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        params.format = PixelFormat.TRANSLUCENT;//设置悬浮球半透明

        params.width = WindowManager.LayoutParams.WRAP_CONTENT;//WRAP_CONTENT表示view的大小和自身内容大小相同
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.TOP | Gravity.LEFT;//设置从哪里开始算view的位置，这里是从左上开始，左上角为坐标(0,0)。
        int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
        //获取屏幕高宽的第二种方法，和第一种方法得到的值相等，单位也是px 像素点
        int screenHeight = context.getResources().getDisplayMetrics().heightPixels;

        params.x = screenWidth/2;//从左上角(0,0)开始，计算view的(x,y)坐标,(x,y)位于自定义view的右下角 对应gravity设置为 TOP LEFT
        params.y = screenHeight - height / 3;//自由控制悬浮view的显示位置

        view.setBackgroundColor(Color.TRANSPARENT);//无背景，背景透明
        Button btn_close = view.findViewById(R.id.fl);

        btn_close.setOnTouchListener(new View.OnTouchListener()
        {//触屏事件监听
            float touchX, touchY;
            int oldOffsetX, oldOffsetY;


            @SuppressLint("RestrictedApi")
            @Override
            //每一个触控事件 DOWN UP MOVE CANCEL都会重新走一遍onTouch
            public boolean onTouch(View v, MotionEvent event)
            {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        oldOffsetX = params.x;//悬浮球在屏幕上的老坐标。
                        oldOffsetY = params.y;
                        touchX = event.getRawX();
                        touchY = event.getRawY();
                        isMoved = false;

                        // 发起长按检查
                        longPressRunnable = new Runnable() {
                            @Override
                            public void run() {
                                handleLongPress();
                            }
                        };
                        handler.postDelayed(longPressRunnable, 400);    // 定时器超时

                        return true;
                    case MotionEvent.ACTION_UP: // 松开检测，若不是移动，则模拟返回键
                        handler.removeCallbacks(longPressRunnable);
                        if (!isMoved) {
                            simulateBack();
                        }
                        break;
                    case MotionEvent.ACTION_MOVE :
                        params.x = oldOffsetX+(int)(event.getRawX() - touchX);
                        params.y = oldOffsetY+(int)(event.getRawY() - touchY);
                        if (params.x-oldOffsetX >  20 || params.y-oldOffsetY >  20)
                        {
                            handler.removeCallbacks(longPressRunnable);
                            isMoved = true;
                            wm.updateViewLayout(view, params);//更新自定义view位置
                        }
                        return true;
                }
                return true;
            }
        });

        try {
            wm.addView(view, params);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this.context, "WindowManager 添加自定义View失败，详情查看打印堆栈", Toast.LENGTH_LONG).show();
        }
    }


    // 长按检测,定时器超时返回桌面
    private void handleLongPress() {
        Intent startMain = new Intent(Intent.ACTION_MAIN);
        startMain.addCategory(Intent.CATEGORY_HOME);
        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(startMain);
        isMoved = true;
    }

    private void simulateBack() {
        // 确保 MyAccessibilityService 已经被初始化并且处于活动状态
        if (MyAccessibilityService.getInstance() != null) {
            MyAccessibilityService.getInstance().performBackPress();
        } else {
            Toast.makeText(this.context, "请打开无障碍权限", Toast.LENGTH_LONG).show();
        }
    }

    // 移除悬浮球
    public void removeFloatView() {
        if (wm != null && view != null) {
            wm.removeViewImmediate(view);

            view = null;
            wm = null;
        }
    }
}
